package com.git.intercepor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.lang3.StringUtils;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;

import com.git.annotation.RequireAuth;
import com.git.constants.Constans;
import com.git.utils.JWTUtils;

/*
 * 这里现在设置为通过
 */
public class UserInteceptor extends HandlerInterceptorAdapter {

	@Override
	public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler)
			throws Exception {
		//如果不是访问method，就直接放过
		if (!(handler instanceof HandlerMethod)) {
			return true;
		}
		
		//如果方法上没有@requireAuth注解，直接放过
		HandlerMethod handlerMethod = (HandlerMethod) handler;
		if (handlerMethod.getMethodAnnotation(RequireAuth.class)==null) {
			return true;
		}
		
		String authHeader = request.getHeader(Constans.AUTHHEADER);
		if (StringUtils.isBlank(authHeader)) {
			//如果头部没有验证内容，就直接拒绝
			response.setStatus(HttpServletResponse.SC_UNAUTHORIZED);
			return false;
		}
		
		String id = JWTUtils.parseJWT(authHeader);
		if (StringUtils.isBlank(id)) {
			//如果验签失败，直接拒绝
			return false;
		}
		
		//最后把id写到request中
		request.setAttribute(Constans.REQUEST_ID, id);
		return true;
	}

}
